import wsgiref.handlers
import os
import random
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from google.appengine.api import users
import urllib
import uzdb
import shared



class MainPage(webapp.RequestHandler):
	def get(self):
		user = users.get_current_user()
		urls = self.page_urls(user)
		top_urls = db.GqlQuery("SELECT * FROM Url WHERE users = :1 ORDER BY counter DESC",user.email()).fetch(5)
		top_slugs = list()
		for u in top_urls:
			top_slugs.append(u.url_id)
		top_domains = db.GqlQuery("SELECT * FROM ReferrerDomain WHERE url_id IN :1",top_slugs)
		template_values = {
					'version': "app_version",
					'message': "",
					'urls': urls,
					'top_urls': top_urls,
					'greeting': shared.get_greeting(),
					'x': 1,
					'style': 'neither'
		}	 
		path = os.path.join(os.path.dirname(__file__), 'dashboard.html')
		self.response.out.write(template.render(path, template_values))
	
	def post(self):
		
		template_values = {
					'version': "app_version",
					'message': "added!",
					'greeting': shared.get_greeting()
		}	 
		path = os.path.join(os.path.dirname(__file__), 'dashboard.html')
		self.response.out.write(template.render(path, template_values))
	
	def page_urls(self,user):
		return db.GqlQuery("SELECT * FROM Url WHERE users = :1 ORDER BY created DESC",user.email()).fetch(25)
  

class UrlDetailPage(webapp.RequestHandler):
	def get(self):
		if not self.request.get('slug'):
			self.response.out.write("Error: invalid request")
			return
		url = db.GqlQuery("SELECT * FROM Url WHERE slug= :1",self.request.get('slug')).get()
		#tweets = db.GqlQuery("SELECT * FROM Tweet WHERE slug= :1 ORDER BY created_at DESC",self.request.get('slug'))
		tweets = db.GqlQuery("SELECT * FROM Tweet WHERE slug= :1",self.request.get('slug'))
		domains = db.GqlQuery("SELECT * FROM ReferrerDomain WHERE url_id=:1 ORDER BY counter DESC",url.url_id)
		domain_chart_data= ''
		domain_chart_keys= ''
		other = float(0)
		for domain in domains:
			pct = float(url.counter) / float(domain.counter)
			if pct >= 5:
				if domain_chart_data != '':
					domain_chart_data = domain_chart_data+','+str(pct)
					domain_chart_keys = domain_chart_keys+'|'+str(domain.domain)
				else:
					domain_chart_data= str(pct)
					domain_chart_keys= str(domain.domain)
			else:
				other = other+pct
		if other > 0:
			domain_chart_data = domain_chart_data+','+str(other)
			domain_chart_keys = domain_chart_keys+'|other'
		if domain_chart_data != '':
			domain_chart = "<img src='http://chart.apis.google.com/chart?chs=660x100&chd=t:"+domain_chart_data+"&cht=p3&chl="+domain_chart_keys+"' />"
		else:
			domain_chart = ''
		template_values = {'url': url,'tweets':tweets,'domain_chart':domain_chart}
		path = os.path.join(os.path.dirname(__file__), 'details.html')
		self.response.out.write(template.render(path, template_values))
	

def main():
	application = webapp.WSGIApplication(
																			 [('/dashboard/details*', UrlDetailPage),
																				('/.*', MainPage)],
																			 debug=True)
	wsgiref.handlers.CGIHandler().run(application)